#!/bin/bash
# login kubernetes container

if [[ $1 == '--help' ]];then
    echo; echo "Usage: $0 <pod_keywords> <namespace>"; echo;
    exit 1
fi

KEYWORDS=${1:-all}

NAMESPACE=${2:-__NAMESPACE}

KUBESERVER=__KUBE_MASTER


if [[ ${KEYWORDS} == "all" ]];then
	PODS=$(kubectl --server=${KUBESERVER} get pods --namespace=${NAMESPACE} | grep -v 'NAME' | cut -d' ' -f1)
	PODSNUM=$(kubectl --server=${KUBESERVER} get pods --namespace=${NAMESPACE} | grep -v 'NAME' | cut -d' ' -f1 | wc -l)
else
	PODS=$(kubectl --server=${KUBESERVER} get pods --namespace=${NAMESPACE} | grep -i ${KEYWORDS} | cut -d' ' -f1)
	PODSNUM=$(kubectl --server=${KUBESERVER} get pods --namespace=${NAMESPACE} | grep -i ${KEYWORDS} | cut -d' ' -f1 | wc -l)
fi


PS3='Choose to restart options(input "q" to exit)> '

select pod in ${PODS};do

    if [[ "$REPLY" =~ ^[0-9]+$ ]] && [ "$REPLY" -ge 1 -a "$REPLY" -le $PODSNUM ];then
        echo -en "##########\\033[1;31m BEGIN \\033[0;39m##########";echo
		cip=$(kubectl --server=${KUBESERVER} describe pods $pod --namespace=${NAMESPACE} | grep IP: | cut -d':' -f2 | xargs -n1)
		sshpass -p 'zxcasd123' ssh -o StrictHostKeyChecking=no root@$cip
    elif [ "$REPLY" == 'q' ];then
        break
    else
        echo -en "##########\\033[1;31m BEGIN \\033[0;39m##########";echo
        echo 'Input error'
    fi

    REPLY=''
    echo;echo -en "##########\\033[1;31m  END  \\033[0;39m##########";echo
done
